const { log } = require('console');
var mysql = require('mysql');
var schema = 'sht_test_oa158gl';
var connection = mysql.createConnection({
  host     : '233.225.233.182',  
  user     : 'sht_test_oa158gl',
  password : 'w2PMnZ8XKjWBwn3y',
  database : 'information_schema'
});
connection.connect();

//类
var cls = {
    //主键一个 field 实例
    primary:null,
    //一个类有多个字段
    //是一个对象，键为字段名，值为字段的对象
    fields : {},
    //父类名字
    parent:null,
    //一个类有多个方法
    methods:[],
    
    //toString 方法
    //输入一个类的文本内容
    toString:function(){
        //父类继承部分
        let parentStr = '';
        if(this.parent != null){
            parentStr = `extends ${this.parent}`;
        }

        //字段内容部分
        let fieldsStr = '';
        for(fieldName in this.fields){
            let f = this.fields[fieldName];
            fieldsStr += f.toString();
        }

        //方法内容部分
        let methodsStr = '';
        for(let i = 0 ; i < this.methods.length; i ++){
            let m = this.methods[i];
            methodsStr += m.toString();
        }

    let template = `
class ${this.name} ${parentStr}
{
${fieldsStr}
${methodsStr}
}
    `;
        return template;
    }
};

/**
 * 方法
 */
var  method ={
    //方法名
    name:null,
    //参数列表
    params:[],
    //方法注释
    comment:null,
    //方法的代码内容
    content:null,
    //访问控制修饰符，默认为 public
    accessControl:'public',
    //返回类型
    returnType:null,
    //输出方法内容
    renderContent:function(){
        //todo 暂时写死
        return `return $this->hasOne(EnterpriseModel::class,'id','enterprise_id');`;
    },
    //输入方法内容
    toString:function(){
        let content = this.renderContent();
        let template = `
        /**
         * @return ${this.returnType}
         */
        ${this.accessControl} function ${this.name}(){
            ${content}
        }
        `;
        return template;
    }
};


//成员变量
var fieldName = {
    //字段访问控制修饰符 ， 暂时定死为 public
    accessControl:'public',
    //字段类型
    type:null,
    //注释
    comment:null,
    //字段名
    fieldName:null,
    //输入字段内容
    toString:function(){
        return `
        /**
         * @var $${this.name} ${this.type}
         */
        ${this.accessControl} $${this.name};
        `;
        console.log(template);
    }
};

// let a = { ... field};
// a.name = 'name';
// a.type = 'int';
// // console.log(a.toString());

// let m = {... method};
// m.name = 'enterprise';
// m.returnType = 'HasOne';
// // console.log(m.toString());

// let c = {... cls};
// c.name = 'UserModel';
// c.fields.push(a);
// c.methods.push(m);
// console.log(c.toString());

/**
 * 将蛇形变量名 parse 为驼峰
 * upperFirst 首字母是否大写
 */
function parseHump(name,upperFirst = true){
    name = name.toLowerCase();
    let r = [];
    let l =  name.split('_');
    for(let i = 0 ; i< l.length ; i ++){
        let item = l[i];
        if(i == 0 && upperFirst == false){
            r.push(item);
            continue;
        }
        let head = item.substring(0,1);
        let tail = item.substring(1);
        r.push(head.toUpperCase() + tail);
    }
    return r.join('');
}


/**
 *将数据库中的一个column数据parse为一个field 实例
 */
function column2field(column){
    let f = {...fieldName};
    f.name = parseHump(column.COLUMN_NAME,false);
    switch(column.DATA_TYPE){
        case 'int':
        case 'tinyint':
            f.type = 'int';
            break;
        case 'varchar':
            f.type = 'string';
            break;
        case 'datetime':
            f.type = 'Carbon';
            break;
        default:
            console.log('不支持的数据库类型:' + column.DATA_TYPE);
            break;
    }
    return f;
}

/**
 * 将驼峰parse为蛇形
 */
function parseSnake(){
    
}

connection.query(`select * from tables where table_schema='${schema}' and table_name = 'customer'`, function (error, results, fields) {
  if (error) {
      console.log('查询表失败');
  }
  for(let i = 0 ; i < results.length;i ++){
      let table = results[i];
      let tableName = table.TABLE_NAME;

      let c = {... cls};
      c.name = parseHump(tableName.toLowerCase());
      c.parent = 'Model';
      
      //查询所有字段
      connection.query(`select * from information_schema.columns where table_schema='${schema}' and table_name='${tableName}'`, function (error, results, fields) {
        if (error) {
            console.log('查询表结构失败:' + tableName);
        }
        
        for(let k = 0 ; k < results.length;k ++){
            let column = results[k];
            let f = column2field(column);
            c.fields[f.name] = f;
            if(k == results.length - 1) {
                console.log(c.toString());
            }
        }
      });
  }
});


//test parse 驼峰命名
// console.log(parseHump('user_name',false));